package com.jichangxiu.server.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jichangxiu.common.annotation.DataScope;
import com.jichangxiu.common.constant.Constant;
import com.jichangxiu.common.entity.bo.PageData;
import com.jichangxiu.common.exception.ServerException;
import com.jichangxiu.common.exception.ServiceException;
import com.jichangxiu.common.utils.RsaUtils;
import com.jichangxiu.common.utils.StrUtils;
import com.jichangxiu.common.utils.TokenUtils;
import com.jichangxiu.framework.mybatis.BaseServiceImpl;
import com.jichangxiu.server.platform.entity.dto.PlatformRoleQueryDto;
import com.jichangxiu.server.platform.entity.dto.PlatformTenantQueryDto;
import com.jichangxiu.server.platform.entity.dto.PlatformUserQueryDto;
import com.jichangxiu.server.platform.entity.map.PlatformRoleBasic;
import com.jichangxiu.server.platform.entity.map.PlatformTenantBasic;
import com.jichangxiu.server.platform.entity.map.PlatformUserBasic;
import com.jichangxiu.server.platform.entity.po.*;
import com.jichangxiu.server.platform.entity.vo.PlatformUserAddVo;
import com.jichangxiu.server.platform.entity.vo.PlatformUserEditVo;
import com.jichangxiu.server.platform.entity.vo.PlatformUserQueryVo;
import com.jichangxiu.server.platform.mapper.PlatformUserMapper;
import com.jichangxiu.server.platform.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * PlatformUserServiceImpl:
 *
 * @author Jcx
 * @create 2023-03-08 21:19
 */
@Service
public class PlatformUserServiceImpl extends BaseServiceImpl<PlatformUserMapper, PlatformUser> implements PlatformUserService {

    @Resource
    private TokenUtils tokenUtils;

    @Resource
    private StrUtils strUtils;

    @Resource
    private PlatformUserMapper platformUserMapper;

    @Autowired
    private PlatformTenantService platformTenantService;

    @Autowired
    private PlatformRoleService platformRoleService;

    @Autowired
    private PlatformMenuPowerService platformMenuPowerService;

    @Resource
    private PlatformUserRoleService platformUserRoleService;

    @Resource
    private PlatformUserPostService platformUserPostService;

    /**
     * 新增用户
     *
     * @param platformUserAddVo 用户视图对象
     * @return 是否成功
     */
    @Override
    public Boolean add(PlatformUserAddVo platformUserAddVo) {
        if (ObjectUtil.isEmpty(platformUserAddVo)) {
            throw ServiceException.build("用户对象无效");
        }

        PlatformUser platformUser = PlatformUserBasic.INSTANCE.toPlatformUser(platformUserAddVo);
        if (ObjectUtil.isEmpty(platformUser)) {
            throw ServiceException.build("用户对象无效");
        }

        if (!Validator.isEmail(platformUser.getEmail())) {
            throw ServiceException.build("用户联系邮箱不符合规范");
        }

        if (!Validator.isMobile(platformUser.getPhone())) {
            throw ServiceException.build("用户联系电话不符合规范");
        }

        if (Constant.PLATFORM_SUPER_USER.equals(platformUser.getUserCode())) {
            throw ServiceException.build("用户标识不能为 PLATFORM_SUPER_USER");
        }

        if (Constant.SYSTEM_SUPER_USER.equals(platformUser.getUserCode())) {
            throw ServiceException.build("用户标识不能为 SYSTEM_SUPER_USER");
        }

        // code 必须唯一
        PlatformUser dbPlatformUserByCode = getOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getUserCode, platformUser.getUserCode()));
        if (ObjectUtil.isNotEmpty(dbPlatformUserByCode)) {
            throw ServiceException.build(platformUser.getNickName() + "该用户的标识重复");
        }

        // phone 必须唯一
        PlatformUser dbPlatformUserByPhone = getOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getPhone, platformUser.getPhone()));
        if (ObjectUtil.isNotEmpty(dbPlatformUserByPhone)) {
            throw ServiceException.build(platformUser.getNickName() + "该用户的手机号码重复");
        }

        // email 必须唯一
        PlatformUser dbPlatformUserByEmail = getOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getEmail, platformUser.getEmail()));
        if (ObjectUtil.isNotEmpty(dbPlatformUserByEmail)) {
            throw ServiceException.build(platformUser.getNickName() + "该用户的邮箱账号重复");
        }

        // username 必须唯一
        PlatformUser dbPlatformUserByName = getOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getUsername, platformUser.getUsername()));
        if (ObjectUtil.isNotEmpty(dbPlatformUserByName)) {
            throw ServiceException.build(platformUser.getNickName() + "该用户的用户账号重复");
        }

        String tenantId = tokenUtils.getTenantId();

        platformUser.setUserNo(strUtils.createNo("user"));
        platformUser.setTenantId(tenantId);
        platformUser.setPassword(new BCryptPasswordEncoder().encode(RsaUtils.decrypt(platformUser.getPassword())));

        boolean b1 = save(platformUser);

        // 保存用户角色关联关系
        boolean b2 = true;
        List<String> roleIds = platformUserAddVo.getRoleIds();
        if (ObjectUtil.isNotEmpty(roleIds)) {
            List<PlatformUserRole> platformUserRoleList = new ArrayList<>();
            roleIds.forEach(roleId -> {
                platformUserRoleList.add(PlatformUserRole.builder().userId(platformUser.getUserId()).roleId(roleId).tenantId(tenantId).build());
            });
            if (ObjectUtil.isNotEmpty(platformUserRoleList)) {
                b2 = platformUserRoleService.saveBatch(platformUserRoleList);
            }
        }

        // 保存用户角色关联关系
        boolean b3 = true;
        List<String> postIds = platformUserAddVo.getPostIds();
        if (ObjectUtil.isNotEmpty(postIds)) {
            List<PlatformUserPost> platformUserPostList = new ArrayList<>();
            postIds.forEach(postId -> {
                platformUserPostList.add(PlatformUserPost.builder().userId(platformUser.getUserId()).postId(postId).tenantId(tenantId).build());
            });
            if (ObjectUtil.isNotEmpty(platformUserPostList)) {
                b3 = platformUserPostService.saveBatch(platformUserPostList);
            }
        }

        return b1 && b2 && b3;
    }

    /**
     * 多选级联删除用户
     *
     * @param userIdList 用户ID列表
     * @return 是否成功
     */
    @Override
    public Boolean del(List<String> userIdList) {
        List<PlatformUser> platformUserList = list(new LambdaQueryWrapper<PlatformUser>().in(PlatformUser::getUserId, userIdList));
        if (ObjectUtil.isEmpty(platformUserList)) {
            throw ServiceException.build("数据库中不存在需要删除的记录");
        }

        platformUserList.forEach(platformUser -> {
            if (Constant.PLATFORM_SUPER_USER.equals(platformUser.getUserCode())) {
                throw ServiceException.build("标识为 PLATFORM_SUPER_USER 的用户不能删除");
            }
            if (Constant.SYSTEM_SUPER_USER.equals(platformUser.getUserCode())) {
                throw ServiceException.build("标识为 SYSTEM_SUPER_USER 的用户不能删除");
            }
        });

        boolean b1 = removeBatchByIds(userIdList);

        boolean b2 = true;
        List<PlatformUserRole> platformUserRoles = platformUserRoleService.list(new LambdaQueryWrapper<PlatformUserRole>().in(PlatformUserRole::getUserId, userIdList));
        if (ObjectUtil.isNotEmpty(platformUserRoles)) {
            List<String> userRoleIds = new ArrayList<>();
            platformUserRoles.forEach(platformUserRole -> userRoleIds.add(platformUserRole.getId()));
            if (ObjectUtil.isNotEmpty(userRoleIds)) {
                b2 = platformUserRoleService.removeBatchByIds(userRoleIds);
            }
        }

        boolean b3 = true;
        List<PlatformUserPost> platformUserPosts = platformUserPostService.list(new LambdaQueryWrapper<PlatformUserPost>().in(PlatformUserPost::getUserId, userIdList));
        if (ObjectUtil.isNotEmpty(platformUserPosts)) {
            List<String> userPostIds = new ArrayList<>();
            platformUserPosts.forEach(platformUserPost -> userPostIds.add(platformUserPost.getId()));
            if (ObjectUtil.isNotEmpty(userPostIds)) {
                b3 = platformUserPostService.removeBatchByIds(userPostIds);
            }
        }
        return b1 && b2 && b3;
    }

    /**
     * 修改用户信息
     *
     * @param platformUserEditVo 用户视图对象
     * @return 是否成功
     */
    @Override
    public Boolean edit(PlatformUserEditVo platformUserEditVo) {
        if (ObjectUtil.isEmpty(platformUserEditVo)) {
            throw ServiceException.build("用户对象无效");
        }

        PlatformUser platformUser = PlatformUserBasic.INSTANCE.toPlatformUser(platformUserEditVo);
        if (ObjectUtil.isEmpty(platformUser)) {
            throw ServiceException.build("用户对象无效");
        }

        PlatformUser dbPlatformUser = getOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getUserId, platformUser.getUserId()));
        if (ObjectUtil.isEmpty(dbPlatformUser)) {
            throw ServiceException.build(platformUser.getNickName() + "该用户在数据库中不存在");
        }

        if (!Validator.isEmail(platformUser.getEmail())) {
            throw ServiceException.build("用户联系邮箱不符合规范");
        }

        if (!Validator.isMobile(platformUser.getPhone())) {
            throw ServiceException.build("用户联系电话不符合规范");
        }

        if (Constant.PLATFORM_SUPER_USER.equals(dbPlatformUser.getUserCode()) && !platformUser.getUserCode().equals(dbPlatformUser.getUserCode())) {
            throw ServiceException.build("标识为 PLATFORM_SUPER_USER 的用户不能修改标识");
        }

        if (Constant.PLATFORM_SUPER_USER.equals(dbPlatformUser.getUserCode()) && !platformUser.getStatus().equals(dbPlatformUser.getStatus())) {
            throw ServiceException.build("标识为 PLATFORM_SUPER_USER 的用户不能修改状态");
        }

        if (Constant.SYSTEM_SUPER_USER.equals(dbPlatformUser.getUserCode()) && !platformUser.getUserCode().equals(dbPlatformUser.getUserCode())) {
            throw ServiceException.build("标识为 SYSTEM_SUPER_USER 的用户不能修改标识");
        }

        if (Constant.SYSTEM_SUPER_USER.equals(dbPlatformUser.getUserCode()) && !platformUser.getStatus().equals(dbPlatformUser.getStatus())) {
            throw ServiceException.build("标识为 SYSTEM_SUPER_USER 的用户不能修改状态");
        }

        // phone 必须唯一
        if (!platformUser.getPhone().equals(dbPlatformUser.getPhone())) {
            PlatformUser dbPlatformUserByPhone = getOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getPhone, platformUser.getPhone()));
            if (ObjectUtil.isNotEmpty(dbPlatformUserByPhone)) {
                throw ServiceException.build(platformUser.getNickName() + "该用户的手机号码重复");
            }
        }


        // email 必须唯一
        if (!platformUser.getEmail().equals(dbPlatformUser.getEmail())) {
            PlatformUser dbPlatformUserByEmail = getOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getEmail, platformUser.getEmail()));
            if (ObjectUtil.isNotEmpty(dbPlatformUserByEmail)) {
                throw ServiceException.build(platformUser.getNickName() + "该用户的邮箱账号重复");
            }
        }

        // username 必须唯一
        if (!platformUser.getUsername().equals(dbPlatformUser.getUsername())) {
            PlatformUser dbPlatformUserByName = getOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getUsername, platformUser.getUsername()));
            if (ObjectUtil.isNotEmpty(dbPlatformUserByName)) {
                throw ServiceException.build(platformUser.getNickName() + "该用户的用户账号重复");
            }
        }

        String tenantId = tokenUtils.getTenantId();

        // 做修改覆盖操作
        BeanUtil.copyProperties(platformUser, dbPlatformUser, true);

        // 数据库已存在的
        List<PlatformUserRole> platformUserRoleList = platformUserRoleService.list(new LambdaQueryWrapper<PlatformUserRole>().in(PlatformUserRole::getUserId, platformUser.getUserId()));
        // 页面传来的
        List<String> roleIdList = platformUserEditVo.getRoleIds();
        // 最终会向数据库中添加的
        List<PlatformUserRole> addPlatformUserRoleList = new ArrayList<>();
        // 会从数据库中删除的
        List<String> deletePlatformUserRoleIdList = new ArrayList<>();

        // 如果两个对象都是空的
        if (ObjectUtil.isEmpty(roleIdList) && ObjectUtil.isEmpty(platformUserRoleList)) {
            // 这种情况啥也不做
        }
        // 如果两个对象都不是空的
        else if (ObjectUtil.isNotEmpty(roleIdList) && ObjectUtil.isNotEmpty(platformUserRoleList)) {
            // 这种情况最为复杂
            // 先处理向数据库中添加的
            for (String roleId : roleIdList) {
                // 默认在数据库中不存在
                boolean flag = false;
                for (PlatformUserRole platformUserRole : platformUserRoleList) {
                    // 如果相等说明在数据库中存在
                    if (roleId.equals(platformUserRole.getRoleId())) {
                        flag = true;
                        break;
                    }
                }
                // 不存在的话就新增
                if (!flag) {
                    addPlatformUserRoleList.add(PlatformUserRole.builder().userId(platformUser.getUserId()).roleId(roleId).tenantId(tenantId).build());
                }
            }
            // 在处理从数据库中删除的
            for (PlatformUserRole platformUserRole : platformUserRoleList) {
                // 默认此条数据库记录不在本次页面对象中
                boolean flag = false;
                for (String roleId : roleIdList) {
                    // 如果相等说明数据库记录在本次页面对象中
                    if (platformUserRole.getRoleId().equals(roleId)) {
                        flag = true;
                        break;
                    }
                }
                // 如果全部循环完成后发现数据库记录没有出现在本次页面提交的数据中，那么说明它已被用户删除
                if (!flag) {
                    deletePlatformUserRoleIdList.add(platformUserRole.getId());
                }
            }
        }
        // 如果一个对象空的，另一个不是空的
        else if (ObjectUtil.isEmpty(roleIdList) && ObjectUtil.isNotEmpty(platformUserRoleList)) {
            // 数据库中的数据全部删除
            platformUserRoleList.forEach(platformUserRole -> deletePlatformUserRoleIdList.add(platformUserRole.getId()));
        }
        // 如果一个对象空的，另一个不是空的
        else if (ObjectUtil.isNotEmpty(roleIdList) && ObjectUtil.isEmpty(platformUserRoleList)) {
            // 页面传来的需要全部在数据库创建
            roleIdList.forEach(roleId -> addPlatformUserRoleList.add(PlatformUserRole.builder().userId(platformUser.getUserId()).roleId(roleId).tenantId(tenantId).build()));
        }

        // 数据库已存在的
        List<PlatformUserPost> platformUserPostList = platformUserPostService.list(new LambdaQueryWrapper<PlatformUserPost>().in(PlatformUserPost::getUserId, platformUser.getUserId()));
        // 页面传来的
        List<String> postIdList = platformUserEditVo.getPostIds();
        // 最终会向数据库中添加的
        List<PlatformUserPost> addPlatformUserPostList = new ArrayList<>();
        // 会从数据库中删除的
        List<String> deletePlatformUserPostIdList = new ArrayList<>();

        // 如果两个对象都是空的
        if (ObjectUtil.isEmpty(postIdList) && ObjectUtil.isEmpty(platformUserPostList)) {
            // 这种情况啥也不做
        }
        // 如果两个对象都不是空的
        else if (ObjectUtil.isNotEmpty(postIdList) && ObjectUtil.isNotEmpty(platformUserPostList)) {
            // 这种情况最为复杂
            // 先处理向数据库中添加的
            for (String postId : postIdList) {
                // 默认在数据库中不存在
                boolean flag = false;
                for (PlatformUserPost platformUserPost : platformUserPostList) {
                    // 如果相等说明在数据库中存在
                    if (postId.equals(platformUserPost.getPostId())) {
                        flag = true;
                        break;
                    }
                }
                // 不存在的话就新增
                if (!flag) {
                    addPlatformUserPostList.add(PlatformUserPost.builder().userId(platformUser.getUserId()).postId(postId).tenantId(tenantId).build());
                }
            }
            // 在处理从数据库中删除的
            for (PlatformUserPost platformUserPost : platformUserPostList) {
                // 默认此条数据库记录不在本次页面对象中
                boolean flag = false;
                for (String postId : postIdList) {
                    // 如果相等说明数据库记录在本次页面对象中
                    if (platformUserPost.getPostId().equals(postId)) {
                        flag = true;
                        break;
                    }
                }
                // 如果全部循环完成后发现数据库记录没有出现在本次页面提交的数据中，那么说明它已被用户删除
                if (!flag) {
                    deletePlatformUserPostIdList.add(platformUserPost.getId());
                }
            }
        }
        // 如果一个对象空的，另一个不是空的
        else if (ObjectUtil.isEmpty(postIdList) && ObjectUtil.isNotEmpty(platformUserPostList)) {
            // 数据库中的数据全部删除
            platformUserPostList.forEach(platformUserPost -> deletePlatformUserPostIdList.add(platformUserPost.getId()));
        }
        // 如果一个对象空的，另一个不是空的
        else if (ObjectUtil.isNotEmpty(postIdList) && ObjectUtil.isEmpty(platformUserPostList)) {
            // 页面传来的需要全部在数据库创建
            postIdList.forEach(postId -> addPlatformUserPostList.add(PlatformUserPost.builder().userId(platformUser.getUserId()).postId(postId).tenantId(tenantId).build()));
        }

        boolean b1 = updateById(dbPlatformUser);

        // addPlatformUserRoleList
        boolean b2 = true;
        if (ObjectUtil.isNotEmpty(addPlatformUserRoleList)) {
            b2 = platformUserRoleService.saveBatch(addPlatformUserRoleList);
        }
        // deletePlatformUserRoleIdList
        boolean b3 = true;
        if (ObjectUtil.isNotEmpty(deletePlatformUserRoleIdList)) {
            b3 = platformUserRoleService.removeBatchByIds(deletePlatformUserRoleIdList);
        }

        // addPlatformUserPostList
        boolean b4 = true;
        if (ObjectUtil.isNotEmpty(addPlatformUserPostList)) {
            b4 = platformUserPostService.saveBatch(addPlatformUserPostList);
        }

        // deletePlatformUserPostIdList
        boolean b5 = true;
        if (ObjectUtil.isNotEmpty(deletePlatformUserPostIdList)) {
            b5 = platformUserPostService.removeBatchByIds(deletePlatformUserPostIdList);
        }

        return b1 && b2 && b3 && b4 && b5;
    }

    /**
     * 根据ID获取用户详情
     *
     * @param userId 用户ID
     * @return 用户详情
     */
    @Override
    public PlatformUserQueryDto info(@NotBlank(message = "用户ID不能为空") String userId) {
        Page<PlatformUser> page = startPage();
        List<PlatformUser> platformUserList = platformUserMapper.pageList(PlatformUser.builder().userId(userId).tenantId(tokenUtils.getTenantId()).build(), page);
        if (ObjectUtil.isEmpty(platformUserList) || platformUserList.size() != 1) {
            throw ServiceException.build(userId + "此数据在数据库中不存在或存在多条");
        }
        PlatformUserQueryDto platformUserQueryDto = PlatformUserBasic.INSTANCE.toPlatformUserQueryDto(platformUserList.get(0));
        List<PlatformUserRole> platformUserRoleList = platformUserRoleService.list(new LambdaQueryWrapper<PlatformUserRole>().in(PlatformUserRole::getUserId, platformUserQueryDto.getUserId()));
        if (ObjectUtil.isNotEmpty(platformUserRoleList)) {
            List<String> roleIds = new ArrayList<>();
            platformUserRoleList.forEach(platformUserRole -> roleIds.add(platformUserRole.getRoleId()));
            platformUserQueryDto.setRoleIds(roleIds);
        }
        List<PlatformUserPost> platformUserPostList = platformUserPostService.list(new LambdaQueryWrapper<PlatformUserPost>().in(PlatformUserPost::getUserId, platformUserQueryDto.getUserId()));
        if (ObjectUtil.isNotEmpty(platformUserPostList)) {
            List<String> postIds = new ArrayList<>();
            platformUserPostList.forEach(platformUserPost -> postIds.add(platformUserPost.getPostId()));
            platformUserQueryDto.setPostIds(postIds);
        }
        return platformUserQueryDto;
    }

    /**
     * 根据租户名和用户名查找用户详情
     *
     * @param tenantName 租户名
     * @param username   用户名
     * @return 用户详情
     */
    @Override
    public PlatformUser getUserByUsername(String tenantName, String username) {
        PlatformTenant platformTenant = getTenantByTenantName(tenantName);
        PlatformUser platformUser = PlatformUser.builder().tenantId(platformTenant.getTenantId()).username(username).build();
        return addAuthToUser(platformUserMapper.getUserByInfo(platformUser));
    }

    /**
     * 根据租户名和手机号查找用户详情
     *
     * @param tenantName 租户名
     * @param phone      手机号
     * @return 用户详情
     */
    @Override
    public PlatformUser getUserByPhone(String tenantName, String phone) {
        PlatformTenant platformTenant = getTenantByTenantName(tenantName);
        PlatformUser platformUser = PlatformUser.builder().tenantId(platformTenant.getTenantId()).phone(phone).build();
        return addAuthToUser(platformUserMapper.getUserByInfo(platformUser));
    }

    /**
     * 根据租户名和邮箱查找用户详情
     *
     * @param tenantName 租户名
     * @param email      邮箱
     * @return 用户详情
     */
    @Override
    public PlatformUser getUserByEmail(String tenantName, String email) {
        PlatformTenant platformTenant = getTenantByTenantName(tenantName);
        PlatformUser platformUser = PlatformUser.builder().tenantId(platformTenant.getTenantId()).email(email).build();
        return addAuthToUser(platformUserMapper.getUserByInfo(platformUser));
    }

    /**
     * 分页查询用户列表
     *
     * @param platformUserQueryVo 用户视图对象
     * @return 分页用户列表
     */
    @Override
    @DataScope
    public PageData<PlatformUserQueryDto> pageList(PlatformUserQueryVo platformUserQueryVo) {
        Page<PlatformUser> page = startPage();
        PlatformUser platformUser = PlatformUserBasic.INSTANCE.toPlatformUser(platformUserQueryVo);
        List<PlatformUser> platformUserList = platformUserMapper.pageList(platformUser, page);
        if (ObjectUtil.isEmpty(platformUserList)) {
            return PageData.build(new Page<>(page.getCurrent(), page.getSize(), page.getTotal()), new ArrayList<>());
        }
        List<PlatformUserQueryDto> platformUserQueryDtoList = PlatformUserBasic.INSTANCE.toPlatformUserQueryDtoList(platformUserList);
        return PageData.build(new Page<>(page.getCurrent(), page.getSize(), page.getTotal()), platformUserQueryDtoList);
    }

    /**
     * 根据租户名称获取租户详情
     *
     * @param tenantName 租户名称
     * @return 租户详情
     */
    private PlatformTenant getTenantByTenantName(String tenantName) {
        PlatformTenantQueryDto platformTenantQueryDto = platformTenantService.getTenantByTenantName(tenantName);
        if (ObjectUtil.isEmpty(platformTenantQueryDto)) {
            throw ServerException.build("查询不到租户名称为" + tenantName + "的租户");
        }
        return PlatformTenantBasic.INSTANCE.toPlatformTenant(platformTenantQueryDto);
    }

    /**
     * 给用户添加权限
     *
     * @param platformUser 用户
     * @return 添加权限后的用户
     */
    private PlatformUser addAuthToUser(PlatformUser platformUser) {
        if (ObjectUtil.isEmpty(platformUser)) {
            throw ServiceException.build("用户不存在");
        }
        List<PlatformRoleQueryDto> platformRoleQueryDtoList = platformRoleService.getRoleListByUser(platformUser.getTenantId(), platformUser.getUserId());
        List<PlatformRole> platformRoleList = PlatformRoleBasic.INSTANCE.toPlatformRoleList(platformRoleQueryDtoList);
        if (ObjectUtil.isNotEmpty(platformRoleList)) {
            platformRoleList = platformRoleList.stream().filter(distinctByKey(PlatformRole::getRoleId)).collect(Collectors.toList());
        }
        platformUser.setPlatformRoles(platformRoleList);

        List<PlatformMenuPower> platformMenuPowerList = platformMenuPowerService.getPowerListByUser(platformUser.getTenantId(), platformUser.getUserId());
        if (ObjectUtil.isNotEmpty(platformMenuPowerList)) {
            platformMenuPowerList = platformMenuPowerList.stream().filter(distinctByKey(PlatformMenuPower::getPowerId)).collect(Collectors.toList());
        }
        platformUser.setPlatformMenuPowers(platformMenuPowerList);
        return platformUser;
    }

    /**
     * 去重
     *
     * @param keyExtractor 条件
     * @param <T>          泛型
     * @return 去重后的数据
     */
    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

}
